package com.fmx.BookStore.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fmx.BookStore.domain.Permission;
import com.fmx.BookStore.domain.Role;
import com.fmx.BookStore.domain.RolePermission;
import com.fmx.BookStore.mapper.RoleMapper;
import com.fmx.BookStore.mapper.RolePermissionMapper;
import com.fmx.BookStore.service.IPermissionService;
import com.fmx.BookStore.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    RoleMapper roleMapper;
    @Resource
    RolePermissionMapper rolePermissionMapper;
    @Resource
    private IPermissionService permissionService;
    @Override
    public Role selectRoleById(Long roleId) {
        return roleMapper.selectRoleById(roleId);
    }

    @Override
    public List<Role> listRole(Role role) {
        return roleMapper.listRole(role);
    }

    @Override
    public int insertRole(Role role) {
        return roleMapper.insertRole(role);
    }

    @Override
    public int updateRole(Role role) {
        return roleMapper.updateRole(role);
    }

    @Override
    public int deleteRole(Long roleId) {
        return roleMapper.deleteRole(roleId);
    }

    @Transactional
    @Override
    public void setRolePermission(Long roleId, List<Long> permissionIds) {
        // 先删除当前角色id所有的绑定关系
        rolePermissionMapper.deleteByRoleId(roleId);

        // 再把前端传过来的菜单id数组绑定到当前的这个角色id上去
        List<Long> permissionIdsCopy = CollUtil.newArrayList(permissionIds);
        for (Long permissionId : permissionIds) {
            Permission permission = permissionService.getById(permissionId);
            if (permission.getPid() != null && !permissionIdsCopy.contains(permission.getPid())) { // 二级菜单 并且传过来的menuId数组里面没有它的父级id
                // 那么我们就得补上这个父级id
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permission.getPid());
                rolePermissionMapper.insert(rolePermission);
                permissionIdsCopy.add(permission.getPid());
            }
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
    }

    @Override
    public List<Long> getRolePermission(Long roleId) {
        return rolePermissionMapper.selectByRoleId(roleId);
    }


}
